package com.monster.starter.core.http.response;

import com.monster.common.http.ResponseData;
import com.monster.json.JsonUtils;
import com.monster.starter.core.common.config.http.HttpResponseConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回数据封装
 *
 * @author kuangxz
 */
@RestControllerAdvice
public class MonsterResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 响应配置
     */
    @Autowired
    private HttpResponseConfig responseConfig;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 单个响应开关
        Response response = returnType.getMethod().getDeclaredAnnotation(Response.class);
        if (response != null) {
            return response.pack();
        }

        // 总开关
        if (responseConfig.isPack()) {
            return true;
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 已经是包装类直接返回
        if (body instanceof ResponseData) {
            return body;
        }
        // 如果是字符串，返回的也要是字符串
        if (body instanceof String) {
            return JsonUtils.toJson(ResponseData.success(body));
        }
        // 默认返回包装类
        return ResponseData.success(body);
    }
}
